<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-09-10 13:51:02
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="g_t('public.edit')"
    width="550px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
      @submit.prevent
    >
      <el-form-item :label="$t('userCenter.orgName')" prop="tname">
        <TextInput v-model="formData.tname" :label="$t('userCenter.orgName')" />
      </el-form-item>
      <el-form-item prop="base64Image">
        <template #label>
          <label>头像</label>
        </template>
        <UploadFile
          style="width: 100%"
          v-model:file-list="fileList"
          :limit="1"
          accept="image/*"
          :on-preview="handlePicturePreview"
          @on-remove="handleRemove"
          @on-success="handleSuccess"
        >
          <el-button type="primary">上传头像</el-button>
        </UploadFile>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>

  <el-image-viewer
    v-if="showPreview"
    :url-list="[formData.base64Image]"
    show-progress
    :initial-index="0"
    @close="showPreview = false"
  />
</template>

<script setup>
const props = defineProps({
  id: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  tid: '',
  tname: '',
  base64Image: '',
  avatar: ''
})
const rules = {
  tname: g_rules.commonInputText(g_t('userCenter.orgName')),
  base64Image: g_rules.uploadFileRule('头像')
}
const fileList = ref([])
// 弹框参数
const showPreview = ref(false)

watch(
  () => formData.value.base64Image,
  nv => {
    refDialogForm.value.validateField(['base64Image'])
  }
)

onMounted(() => {
  getFormData()
})

const getFormData = () => {
  formLoading.value = true
  g_api.userCenter
    .apiTenantDetail({
      tenantId: props.id
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        g_utils.assignFormData(formData.value, data.tenant)
        formData.value.base64Image = data.tenant.avatar
        if (data.tenant.avatar) {
          fileList.value = [
            {
              name: data.tenant.avatar,
              url: data.tenant.avatar
            }
          ]
        }
        // console.log('formData.value', formData.value)
      }
    })
    .finally(_ => {
      formLoading.value = false
    })
}

const handleClose = () => {
  dialogVisible.value = false
}

const handlePicturePreview = file => {
  console.log('handlePicturePreview', file)
  showPreview.value = true
}

const handleRemove = file => {
  console.log('handleRemove', file)
  formData.value.base64Image = ''
  formData.value.avatar = ''
}

const handleSuccess = (res, file, files) => {
  console.log('handleSuccess', res, file, files)
  if (res.code === '200' && res.data) {
    formData.value.avatar = res.data.url
    // 读取新选择的文件并添加到预览数组
    const reader = new FileReader()
    reader.onload = e => {
      formData.value.base64Image = e.target.result
    }
    reader.readAsDataURL(file.raw)
  } else {
    formData.value.base64Image = ''
    formData.value.avatar = ''
  }
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    // console.log('handleSubmitForm', formData.value)
    if (!valid) return
    formLoading.value = true
    g_api.userCenter
      .apiTenantEdit(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss"></style>
